<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cron extends CI_Controller {


	function __construct()
	{
		parent::__construct();
//		$this->output->enable_profiler(TRUE);
		//ignore_user_abort(true);
		//set_time_limit(0);
		$this->load->model('Site_m','site');
		$this->load->model("Cron_m", "cron");
		$this->load->library('session');
		$this->load->helper('url');
	}

	function index()
	{

	}

	function check_session_data(){
		$last_activity = $this->session->userdata('last_activity');
		if (time() - $last_activity > 90){
			$this->session->unset_userdata('site_ids');
			$this->session->unset_userdata('site_info');
		}
	}

	function show_craw_finish_info(){
		$site_info = array();
		$session_site_info = $this->session->userdata('site_info');
		if($session_site_info){
			$site_info = $session_site_info;
		}
		$data = array(
			'finished' => TRUE, 
			'interval' => 86400000,
			'site_info' => $site_info);
		$this->load->view('cron', $data);
	}

	function get_session_crawed_site(){
		$site_ids = $this->session->userdata('site_ids');
		if ($site_ids){
			$crawed_sites = $site_ids;
		} else {
			$crawed_sites = array();
		}
		return $crawed_sites;
	}

	function craw_all(){
		$this->check_session_data();
		log_message("error", "START CRAW ALL SITES");
		$condition = array('status' => 1);
		$sites = $this->site->get_site($condition);
		$this->_batch_craw($sites);
	}

	function regular_craw_init(){
		// load a view to refresh the page
		$site_info = array('sn' => '', 'gc' => 0);
		$data = array(
				'finished' => FALSE, 
				'interval' => 3000,
				'site_info' => $site_info);
		$this->load->view('cron', $data);
	}

	function regular_craw(){
		$start_time = time();
		$this->check_session_data();
		log_message("error", "START REGULAR CRAW SITES");
		$sites = $this->site->get_craw_sites();

		$this->_batch_craw($sites, TRUE, $start_time);
	}

	function _batch_craw($sites, $is_redirect=FALSE, $start_time=0){
		log_message("error", "Total craw " . count($sites) . " sites");
		foreach ($sites as $site){
			$crawed_sites = $this->get_session_crawed_site();
			if($site->id > 0 && !in_array(strval($site->id), $crawed_sites)){
				$continue_craw = $this->_docraw($site, $is_redirect, count($sites), $start_time);
				if (! $continue_craw ){
					break;
				}
			}
		}
		$this->show_craw_finish_info();
	}

	function craw($site_id){
		$this->check_session_data();
		log_message("error", "START SPECIFIED SITE CRAWING<$site_id>");
		$site_id = intval($site_id);
		if($site_id > 0){
			$site_infos = $this->site->get_site(array('id' => $site_id));
			if ($site_infos && is_array($site_infos) && count($site_infos) == 1){
				$this->_docraw($site_infos[0], FALSE, 999, 0);  // 999 is magic number
			}
		}
		$this->show_craw_finish_info();
	}

	function _docraw($site, $is_redirect, $site_count, $start_time){
		$start_time = time();
		$site_id = $site->id;
		if($site_id > 0){
			log_message("error", "START CRAW SITE <$site_id>");

			$goods = $this->cron->craw_data($site_id);
			$good_count = count($goods);
			$crawed_site = $this->add_crawed_site($site_id, $site->site_name, $good_count);

			$craw_succ = TRUE;
			if ($goods){
				if (!$this->cron->import_goods($goods, $site_id, $start_time)){
					$craw_succ = FALSE;
				}
			}else{
				$craw_succ = FALSE;
			}
			if ($craw_succ){
				$this->site->craw_site_succ($site_id);
			}else{
				$this->site->craw_site_fail($site_id);
			}
			log_message("error", "FINISH CRAW SITE <$site_id>");

            unset($goods);
			$site_info = array('sn' => $site->site_name, 'gc' => $good_count);
			$data = array(
					'finished' => FALSE, 
					'interval' => 3000,
					'site_info' => $site_info);
			$this->load->view('cron', $data);
			return FALSE;
		}
	}

	function add_crawed_site($site_id, $site_name, $good_count){
		$site_ids = $this->session->userdata('site_ids');
		if (!$site_ids){
			$site_ids = array();
		}
		if (!in_array($site_id, $site_ids)){
			$site_ids[] = $site_id;
			$this->session->set_userdata('site_ids', $site_ids);

			$site_info = $this->session->userdata('site_info');
			if (!$site_info){
				$site_info = array();
			}
			$site_info[] = array('sn' => $site_name, 'gc' => $good_count);
			$this->session->set_userdata('site_info', $site_info);
		}
		return $site_ids;
	}
	
	function mail(){
		$this->load->model('dx_auth/User_profile','profile');
		$this->load->model('Goods_m','goods');
		$this->load->library('email');
		$send_mail = $this->config->item('DX_webmaster_email');
		$this->load->model('City_m','city');
		
		$all_city = $this->city->get_all_map();
		$max_id = $this->profile->get_max_id();
		$today = date("Y年n月j日");
		$link_prefix = site_url('show/mail').'/';
		
		$step = 500;
		for($i=0; $i<($max_id+$step); $i+=$step){
			$users_info = $this->profile->get_mail_user($i+1,$i+$step);
			$this->_get_mail_info($users_info);

			foreach ($users_info as $user_id => $user){
				$new_good = $this->goods->get_goods($user['city_id'], $user['cat'],true, 'start_time desc',0,1);
				$to_close_good = $this->goods->get_goods($user['city_id'], $user['cat'],true, 'close_time',0,1);
				if(!$new_good){
					continue;
				}
				
				$data = array(
								'today' => $today,
								'city' => $all_city[$user['city_id']],
								'site' => str_replace('/index.php','',site_url()).'/code/',
								'link_prefix' => $link_prefix,
								'new_good' => $new_good[0],
								'to_close_good' => $to_close_good[0]
							 );
				$mail_content = $this->load->view('mail',$data,true);
//				var_dump($data);
//				var_dump($mail_content);
				
				$this->_mail_send($send_mail, $user['email'], $mail_content);
			}
			 
			unset($users_info);
		}
	}

	function _get_mail_info(&$users_info = array()){
		if(!is_array($users_info) || empty($users_info)){
			return array();
		}
		
		$user_ids = array_keys($users_info);
		
		$this->load->model('dx_auth/Users','users');
		$users_mail = $this->users->get_mail_user_info($user_ids);
		
		$this->load->model('Category_m','category');
		$users_category = $this->category->get_users_valid_category($user_ids);
		
		$ban_users = array();
		foreach ($users_info as $user_id => $user){
			if(isset($users_mail[$user_id]) && $users_mail[$user_id]
				&& isset($users_category[$user_id]) && !empty($users_category[$user_id])){
				$users_info[$user_id]['email'] = $users_mail[$user_id];
				$users_info[$user_id]['cat'] = $users_category[$user_id];
			}else{
				$ban_users[] = $user_id;
			}
		}
		
		foreach ($ban_users as $ban_id){
			unset($users_info[$ban_id]);
		}
	}
	
	function _mail_send($from, $to, $content){
		if($to){
		    $this->email->clear();
		    $this->email->to($to);
		    $this->email->from($from);
		    $this->email->subject(SITE_NAME.' 团购精品推荐');
		    $this->email->message($content);
		    $this->email->send();
//		    echo $this->email->print_debugger();
		}
	}
}

/* End of file cron.php */
/* Location: ./application/controllers/cron.php */
